package blackstar.agent.event;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author RayWoo (ayufox@gmail.com)
 * 
 */
public class DefaultEventMediator extends EventMediator
{
	private final static Log LOGGER = LogFactory
			.getLog(DefaultEventMediator.class);

	private Map<Class, List<EventListener>> listeners = new ConcurrentHashMap<Class, List<EventListener>>();

	public void dispatch(Event event)
	{
		LOGGER.info("dispatch event[" + event + "]");
		
		List<EventListener> listeners = this.listeners.get(event.getClass());
		if (listeners != null)
		{
			for (EventListener listener : listeners)
			{
				try
				{
					listener.onEvent(event);
				} catch (Exception e)
				{
					LOGGER.error(listener + " Error onEvent(" + event + ")", e);
				}
			}
		}
	}

	public void register(EventListener eventListener)
	{
		Class[] events = eventListener.events();
		for (Class event : events)
		{
			List<EventListener> list = listeners.get(event);
			if (list == null)
			{
				list = new ArrayList<EventListener>();
				listeners.put(event, list);
			}
			list.add(eventListener);
			list = null;
		}
	}
}
